<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose title="按任务登记" width="100%" :defaultFullscreen="true" :okButtonProps="{ loading: okLoading, }">
    <div class="flex">
      <BasicTree class="w-1/5" title="工单类型" :treeData="treeData" @select="handleWorkTreeSelect" />
      <div class="w-4/5">
        <BasicForm @register="registerForm" />
        <div class="flex">
          <BasicTree class="w-1/7" title="人员选择" :treeData="userTree" @select="handleUserTreeSelect" />
          <div class="w-6/7">
            <!--引用表格-->
            <BasicTable @register="registerTable">
              <!--插槽:table标题-->
              <template #tableTitle>
                <a-button type="primary" preIcon="ant-design:plus-outlined"> 新增</a-button>
              </template>
              <template #bodyCell="{ column, text, record, index }">
                <template v-if="column.editRow">
                  <a-input-number :disabled="isView" v-model:value="record[column.dataIndex]" @change="scoreCompute" v-if="'InputNumber' === column.editComponent && column.dataIndex === 'unit'" @focus="handleIndex(index)" :min="1" />
                  <a-input-number :disabled="isView" v-model:value="record[column.dataIndex]" @change="scoreCompute" v-if="'InputNumber' === column.editComponent && column.dataIndex === 'qspoints'" @focus="handleIndex(index)" />
                  <a-select :disabled="isView" v-model:value="record[column.dataIndex]" style="width: 100%" @change="scoreCompute" @focus="handleIndex(index)" :options="column.options" :fieldNames="{ label: 'workName', value: 'workCode' }" v-else-if="'Select' === column.editComponent" />
                  <a-input :disabled="isView" v-model:value="record[column.dataIndex]" @change="scoreCompute" v-else-if="column.dataIndex === 'workExpl'" />
                </template>
              </template>
              <!--操作栏-->
              <template #action="{ record, index }">
                <TableAction :actions="getTableAction(record, index)" />
              </template>
              <template #toolbar>
                <a-button type="default" danger> 危险 </a-button>
              </template>
            </BasicTable>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <a-button type="primary" @click="handleSubmit">保存</a-button>
      <a-button @click="closeModal">关闭</a-button>
    </template>
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, unref, h } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicTable, TableAction } from '/@/components/Table';
import { FormSchema,BasicForm,useForm } from '/@/components/Form';
import { useListPage } from '/@/hooks/system/useListPage';
import { taskColumns } from './HubTeamResultWork.data';
import { list, createPoints, getOptions, getTaskContentDetail, getTaskDetail, showModeSelect, getWorkTreeApi, getUserTreeApi, getColumn, save, getWorkTreeList, getBaseRelTreeList, } from './HubTeamResultWork.api';
import { BasicTree, ContextMenuItem } from '/@/components/Tree/index';
import { useMessage } from '/@/hooks/web/useMessage'; // 轻提醒
const { createMessage: $message } = useMessage(); // 解构
const queryParam = reactive<any>({});
import dayjs from 'dayjs';
import { unifyNumber } from '/@/views/zhc/util/numUtils';

const taskForm: FormSchema[] = [
  {
    field: 'workItemName',
    label: '工作项',
    component: 'Input',
    dynamicDisabled: () => true,
    colProps: { span: 8 },
  },
  {
    field: 'workItemCode',
    label: '工作项目编码',
    component: 'Input',
    show: false,
  },
  {
    field: 'endDate',
    label: '工作时间',
    component: 'DatePicker',
    componentProps: {
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
    },
    defaultValue: dayjs(),
    required: true,
    colProps: { span: 8 },
    dynamicDisabled: () => isView.value,
  },
  {
    field: 'standardValue',
    label: '标准分值',
    component: 'Input',
    colProps: { span: 8 },
    dynamicDisabled: () => true,
  },
  {
    field: 'workQualityCriterion',
    label: '工作质量标准',
    component: 'InputTextArea',
    dynamicDisabled: () => true,
    labelWidth: '18%',
    show: true,
    colProps: { span: 24 },
  },
];

//注册table数据
const { prefixCls, tableContext, onExportXls, onImportXls, } = useListPage({
  tableProps: {
    title: '按任务登记',
    api: list,
    columns: taskColumns,
    canResize: false,
    // dataSource: mockDate,
    showIndexColumn: true,
    beforeFetch: (params) => {
      return Object.assign(params);
    }, //表格和查询条件同步更新的方法
    // formConfig: {
    //   //labelWidth: 120,
    //   schemas: taskForm,
    //   showResetButton: false,
    //   showSubmitButton: false,
    //   autoSubmitOnEnter: false,
    //   showAdvancedButton: false,
    //   fieldMapToNumber: [],
    //   fieldMapToTime: [['sendTime', ['beginDate', 'endDate'], 'YYYY-MM-DD']],  //日期框转换 
    // },
    actionColumn: {
      width: 60,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: 'right',
    },
    immediate: false,
  },
});
const [registerTable, { getForm, reload, getDataSource, getColumns, setColumns, setTableData }, { rowSelection, selectedRowKeys }] = tableContext;

const [registerForm, { setFieldsValue, validate, resetSchema, getFieldsValue, updateSchema },] = useForm({
  schemas: taskForm,
  showActionButtonGroup: false,
  labelWidth: 180,
});

// Emits声明
const emit = defineEmits(['register', 'success']);


let isView = ref(false);
const codeDetail = ref('1111111111111');
const treeData = ref([]);
let workTreeList = ref([]);
let currentTableIndex = 0; //记录当前操作的表格数据行
let userList: any = ref([]);
let workTree: any = ref([]);
let userTree: any = ref([]);   //人员列表
let workList: any = ref(null);

let rationFormValue = '3'; //工作标准类型 1代表数量积分 2代表 数量+质量积分 3代表质量积分
let selectedUser = {
  addMode: '10',
};

let selectorField = ref([]);
let defaultData = {};
let editid = null;

const props = defineProps({
  self: {
    type: String,
  },
});
const okLoading = ref(false);
const handleIndex = (index) => {
  currentTableIndex = index;
};

//弹框初始化
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  // debugger
  console.log('接收到的数据为444444444：', data);
  queryParam.periodCode = data?.periodCode;
  queryParam.orgCode = data?.orgCode;
  queryParam.orgName = data?.orgName;

  let params = {
    orgCode: queryParam.orgCode,
    periodCode: queryParam.periodCode?.slice(0, 4),
  }
  treeData.value = await getWorkTreeList(params);

  // codeDetail.value = '11111111';

  okLoading.value = false;
  getWorkTreeList(params).then((res) => {
    workTreeList.value = res;
  });
  getBaseRelTreeList(queryParam).then((res) => {
    userTree.value = res;
  });
  editid = data.isEdit ? data.res.id : null;
  userTree.value.disabled = data.isView;
  workTree.disabled = data.isView;
  isView.value = data.isView;
  if (data.isEdit) {
    // 编辑状态
    let formSchema = [...taskForm];
    resetSchema(formSchema);
    setFieldsValue({
      workItemName: data.res.rationName,
      workItemCode: data.res.rationCode,
      endDate: dayjs(data.res.endDate),
      standardValue: data.res.stdscore,
      workQualityCriterion: data.res.qstandard,
    });
    workList.value.handleSelect(data.res.rationCode);
    userList.value.setTreeSelected(data.res.psnNum.split(','));
    queryParam.workId = data.res.rationCode;
    let tableData = data.res.details || [];
    tableData = tableData.map((item) => {
      if (item.reamrk) {
        return {
          ...item,
          ...JSON.parse(item.reamrk),
        };
      }
    });
    setTableData(tableData);
  }
  //动态表头设置 getTeamResultOrderXsHeader
  await getColumn({ orgCode: queryParam.orgCode }).then((res) => {
    let columns = [...taskColumns];
    try {
      res.forEach((r) => {
        //默认值设置
        if (r.datas && r.datas.length > 0) {
          r.datas.forEach((option) => {
            option.workName = option.workName + '(' + option.workCode + ')';
            if (option.isDefault === 'true' && !data.isEdit) {
              defaultData[r.headCode] = option.workCode;
            }
          });
        }
        // 在表格固定表头中插入动态表头
        columns.splice(columns.length - 5, 0, {
          title: r.headName,
          dataIndex: r.headCode,
          editRow: true,
          editComponent: 'Select',
          type: 2,
          width: 100,
          align: 'center',
          options: r.datas,
        });
      });
      setColumns(columns); //重设表头
    } catch (e) {
      console.error(e);
    }
  });
});


/**
 * author:lhw
 * description: 项目树选择事件
 * @params: @
 * date: 2023/3/8
 * lastModify: 2023/3/8
 */
// async function handleWorkTreeSelect(node) {
//   debugger
//   $message.info("点击了树+"+node.data.isRation)
//   // let workTypeDesc = workTreeList.value.filter((item) => item.code === node.data.parentCode)[0].title;
//   setTableData([]); //清空表格数据
//   userList.value.setTreeSelected([]); //清空用户选择数据
//   let formSchema = [...taskForm];
//   resetSchema(formSchema); //先要改变表单对象否则下次重填之前数据更新不上去
//   currentRationCode = node.data.code;
//   //判断是否可查询数据节点
//   if (node.data.isRation) {
//     getTaskDetail({ code: node.data.id }).then(async (res) => {
//       //表单赋值
//       setFieldsValue(res); //得到标准工分 stdscore
//     });
//   }
// };


/**
 * 点击树节点事件
 */
async function handleWorkTreeSelect(keys) {
  // debugger
  $message.info("点击了-工单类型树+" + keys)
  if (keys[0] != null) {
    let key = keys[0];
    queryParam.workId = key;
    let res = await getTaskDetail({ id: key });
    //表单赋值
    setFieldsValue(res);
  }
}

/**
 * 点击树节点事件
 */
 async function handleUserTreeSelect(keys, { selected,selectedNodes, node, event }){
  // debugger
  if (!queryParam.workId) {
    $message.warning('请先选择左侧项目类型');
    return;
  }
  $message.info("点击了-人员树+" + keys)

  let selectPerson = getDataSource();
  let formData = getFieldsValue();
  //计算总分
  let sumPoints:any = 1;
  Object.values(defaultData).forEach((value:any) => {
    sumPoints = unifyNumber(parseFloat(value) * sumPoints);
  });
  sumPoints = unifyNumber(sumPoints * parseFloat(formData.standardValue));
  selectPerson.push({
    psnNum: node.value,
    psnName: node.label,
    unit: 1,
    sumPoints,
    workPoints: sumPoints,
    ...defaultData,
  });

  //重填表格数据
  setTableData(selectPerson);

  // if (keys[0] != null) {
  //   let id = keys[0];
  //   let res = await getTaskDetail({ id: id });
  //   //表单赋值
  //   setFieldsValue(res);
  // }
}


const scoreCompute = () => {
  let TableData = getDataSource();
  let column = getColumns();
  // TableData[]
  let currentRecord = TableData[currentTableIndex];
  let workPoints: any = null;
  if (!currentRecord.unit) {
    // 次数没填时 工作量得分为0    workPoints 工作量得分   qspoints质量得分
    currentRecord.workPoints = 0;
    currentRecord.sumPoints = currentRecord.workPoints;
  } else {
    // currentRecord.workPoints = currentRecord.rationForm
    workPoints = currentRecord.unit;
    column.forEach((c) => {
      if (c.type && currentRecord[c.dataIndex]) {
        workPoints = currentRecord[c.dataIndex] * workPoints;
        // counts.push
      }
    });
    currentRecord.workPoints = workPoints;
    currentRecord.sumPoints = currentRecord.workPoints;
  }
  if (getFieldsValue().standardValue || getFieldsValue().standardValue == 0) {
    currentRecord.workPoints = currentRecord.workPoints * parseFloat(getFieldsValue().standardValue);
  }
  if (currentRecord.qspoints || currentRecord.qspoints == 0) {
    currentRecord.sumPoints = currentRecord.qspoints + currentRecord.workPoints;
  }
  if (!currentRecord.qspoints) {
    currentRecord.sumPoints = currentRecord.workPoints;
  }
  // 精度转化
  currentRecord.workPoints = unifyNumber(currentRecord.workPoints);
  currentRecord.sumPoints = unifyNumber(currentRecord.sumPoints);
};



/**
 * 实体类点击事件
 */
function handleEntityClick(item) {
  $message.info('实体类跳转中....' + item);
}


/**
 * 删除事件
 */
async function handleDelete(record, index) {
  let tableData = getDataSource();
  tableData.splice(index, 1);
  setTableData(tableData);
}

/**
 * 成功回调
 */
function handleSuccess() {
  (selectedRowKeys.value = []) && reload();
}

/**
 * 表格操作栏
 */
function getTableAction(record, index) {
  return [
    {
      label: '删除',
      onClick: handleDelete.bind(null, record, index),
    },
  ];
}


//表单提交事件
async function handleSubmit() {
  try {
    let tableData = getDataSource();
    if (tableData.length === 0) {
      $message.error('数据不能为空！');
      return;
    }
    let flag = true;
    //校验积分是否有空值
    if (!flag) {
      $message.error('积分项不能为空');
      return;
    }
    setModalProps({ confirmLoading: true });
    //拼接参数
    let formValue = await validate();
    let saveData = {
      addMode: '10',
      periodCode: queryParam.periodCode,
      orgCode: queryParam.orgCode,
      orgName: queryParam.orgName,
      workId: queryParam.workId,
      endDate: dayjs(formValue.endDate).format('YYYY-MM-DD'),
      details: tableData,
      descr: formValue.workQualityCriterion,
      qstandard: formValue.workQualityCriterion,
      stdscore: formValue.standardValue,
    };
    saveData.details?.forEach((item) => {
      // let sumScore = 0;
      item.reamrk = {};
      Object.keys(item).forEach((key) => {
        if (key.indexOf('XSP') != -1) {
          // sumScore += parseFloat(item[key]);
          item.reamrk = {
            ...item.reamrk,
            [key]: item[key],
            // sumPoints: sumScore,
          };
        }
        // item.sumPoints = sumScore;
      });
    });
    saveData.details?.forEach((item) => {
      if (item.reamrk) {
        item.reamrk = JSON.stringify(item.reamrk);
      }
    });
    if (editid) {
      saveData.id = editid;
    }
    // changeLoading(true);
    // changeOkLoading(false);
    okLoading.value = true;
    save(saveData).then((res) => {
      if (res) {
        //关闭弹窗
        closeModal();
        okLoading.value = false;
        //刷新列表
        emit('success');
      }
    });
  } finally {
    setModalProps({ confirmLoading: false });
  }
}

</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-calendar-picker) {
  width: 100%;
}
</style>